<?php
namespace app\thirdclass;

use app\helpclass\KafkaReporter;
use Yii;
use Zipkin\Endpoint;
use Zipkin\Propagation\DefaultSamplingFlags;
use Zipkin\Reporters\Http;
use Zipkin\Reporters\Http\CurlFactory;
use Zipkin\Samplers\BinarySampler;
use Zipkin\TracingBuilder;

/**
 * 封装下 zipkin 调用链记录的方法
 * Class Zipkin
 * @package app\thirdclass
 */
class Zipkin
{
    public $endpoint_url;
    public $endpoint_name;

    public function __construct()
    {
        $this->endpoint_url = Yii::$app->params['endpoint_url'];
        $this->endpoint_name = Yii::$app->params['endpoint_name'];
    }

    /**
     * 创建一个记录trace对象
     * @param $endpointName
     * @return \Zipkin\DefaultTracing
     */
    public function createTracing()
    {
        $ipv4 = array_key_exists('REMOTE_ADDR', $_SERVER) ? $_SERVER['REMOTE_ADDR'] : null;
        $endpoint = Endpoint::create($this->endpoint_name,$ipv4);

        //报告发送方式
        //通过curl形式
        $reporter = new Http(CurlFactory::create(),[
            'endpoint_url' => $this->endpoint_url
        ]);
        //通过kafka形式
        //$reporter = new KafkaReporter();
        $sampler = BinarySampler::createAsAlwaysSample();
        $tracing = TracingBuilder::create()
            ->havingLocalEndpoint($endpoint)
            ->havingSampler($sampler)
            ->havingReporter($reporter)
            ->build();

        return $tracing;
    }
}